package com.jarvis.hospital.patient;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jarvis.hospital.R;
import com.jarvis.hospital.SettingActivity;
import com.jarvis.hospital.common.BaseFragment;
import com.jarvis.hospital.common.ResponseData;
import com.jarvis.hospital.login.model.LoginModel;
import com.jarvis.hospital.login.model.UserModel;
import com.jarvis.hospital.patient.adapter.MessageMainAdapter;
import com.jarvis.hospital.patient.adapter.PatientTaskAdapter;
import com.jarvis.hospital.patient.model.MessageListModel;
import com.jarvis.hospital.patient.model.MessageModel;
import com.jarvis.hospital.patient.model.TaskListModel;
import com.jarvis.hospital.patient.model.TaskModel;
import com.jarvis.hospital.servers.ApiService;
import com.jarvis.hospital.util.DividerItemDecoration;
import com.jarvis.hospital.util.SharePreferenceKey;
import com.jarvis.hospital.util.SharePreferenceUtils;
import com.jarvis.hospital.util.net.RequestApi;

import java.util.ArrayList;

import butterknife.BindView;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by jarvis.liu on 2016-11-02.
 */

public class PatientTaskFragment extends BaseFragment {
    private ApiService service;
    @BindView(R.id.recy_task)
    RecyclerView recy_task;
    @BindView(R.id.ptr_task)
    PtrClassicFrameLayout ptr_task;
    private PatientTaskAdapter patientTaskAdapter;
    private int pageSize = 10;
    private int currentPage = 1;
    private int maxPage = 1;

    @BindView(R.id.rel_left)
    RelativeLayout rel_left;
    @BindView(R.id.rel_right)
    RelativeLayout rel_right;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_right)
    TextView tv_right;

    public static PatientTaskFragment newInstance() {
        Bundle args = new Bundle();
        PatientTaskFragment fragment = new PatientTaskFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_patient_task;
    }

    @Override
    public void initData() {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            setStatus(true);
            ptr_task.postDelayed(
                    new Runnable() {
                        @Override
                        public void run() {
                            ptr_task.autoRefresh();
                        }
                    }, 100);
        }

    }

    @Override
    protected void initView() {
        setStatus(true);
        tv_title.setText("用药列表");
        rel_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        service = RequestApi.create(ApiService.class);
        setStatus(true);
        setAdapter();
        setRefresh();
        recy_task.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                TaskModel messageModel = patientTaskAdapter.getData().get(i);
            }
        });
        UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
        String userRole = userModel.getUserRole();
        if("patient".equals(userRole)){
            rel_left.setVisibility(View.GONE);
            tv_right.setText("设置");
            rel_right.setVisibility(View.VISIBLE);
            rel_right.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(SettingActivity.class);
                }
            });
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        ptr_task.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        ptr_task.autoRefresh();
                    }
                }, 100);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    /**
     * 设置下拉刷新
     */
    public void setRefresh() {
        ptr_task.setMode(PtrFrameLayout.Mode.BOTH);
        ptr_task.disableWhenHorizontalMove(true);
        ptr_task.setLastUpdateTimeRelateObject(this);
        ptr_task.setPtrHandler(new PtrDefaultHandler2() {

            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                return PtrDefaultHandler2.checkContentCanBePulledUp(frame, recy_task, footer);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler2.checkContentCanBePulledDown(frame, recy_task, header);
            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                if (currentPage < maxPage) {
                    currentPage++;
                    loadData();
                } else {
                    ptr_task.refreshComplete();
                }
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                patientTaskAdapter.setNewData(new ArrayList<TaskModel>());
                currentPage = 1;
                loadData();
            }
        });
    }

    /**
     * 设置adapter
     */
    public void setAdapter() {
        patientTaskAdapter = new PatientTaskAdapter(R.layout.item_patient_task, new ArrayList<TaskModel>());
        recy_task.setLayoutManager(new LinearLayoutManager(getActivity()));
        recy_task.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST, getResources().getDrawable(R.drawable.divier_order_gray)));
        patientTaskAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        recy_task.setAdapter(patientTaskAdapter);
    }

    private void loadData() {
        UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
        String userId = userModel.getUserId();
        service.getMedicineList(currentPage, pageSize, userId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData<TaskListModel>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData<TaskListModel> taskListModelResponseData) {
                        if (taskListModelResponseData != null) {
                            int resultCode = taskListModelResponseData.getResultCode();
                            if (resultCode == 200) {
                                int total_count = taskListModelResponseData.getTotalcount();
                                maxPage = total_count % pageSize == 0 ? total_count / pageSize : total_count / pageSize + 1;
                                patientTaskAdapter.addData(taskListModelResponseData.getData().getMedicineList());
                            } else {
                                showTextToast(taskListModelResponseData.getMessage());
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ptr_task.refreshComplete();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        ptr_task.refreshComplete();
                    }
                });
    }
}
